

//
//  HMOAuthViewController.m
//  黑马微博-wzy
//
//  Created by Mac on 2017/2/7.
//  Copyright © 2017年 Mac. All rights reserved.
//

#import "HMOAuthViewController.h"
#import "MBProgressHUD+MJ.h"
#import "HMTabBarViewController.h"
//新特性:第一次使用该版本
#import "HMNewFeatureViewController.h"
#import "HMControllerTool.h"
#import "HMAccountTool.h"
#import "HMHttpTool.h"

@interface HMOAuthViewController ()<UIWebViewDelegate>

@end

@implementation HMOAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = self.view.bounds;
    [self.view addSubview:webView];
    
    NSString *url = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@", HMAppKey, HMRedirectUrl];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    webView.delegate = self;
    [webView loadRequest:request];
}

#pragma mark - UIWebViewDelegate
//UIWebView 开始加载的时候调用
- (void)webViewDidStartLoad:(UIWebView *)webView{

    [MBProgressHUD showMessage:@"正在加载中..."];
}
//UIWebView 加载结束的时候调用
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideHUD];
}
//UIWebView 加载失败的时候调用
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [MBProgressHUD hideHUD];
}

//UIWebView 每当发送一个请求之前,都会调用这个代理方法(询问代理是否允许加载这个请求)
//request:即将发送的请求
//YES:允许加载; NO:禁止加载
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

//    HMLog(@"request:%@", request);
    //登录成功的回调地址
    //request:<NSMutableURLRequest: 0x608000016ad0> { URL: http://www.itheima.com/?code=946ff7e74049130840914936d67064c8 }
    //1/获取请求地址
    NSString *url = request.URL.absoluteString;
    //2
    NSRange range = [url rangeOfString:@"http://www.itheima.com/?code="];
//    range.location;
//    range.length;
    if (range.location != NSNotFound) {
        //是回调地址
        int from = range.location + range.length;
        NSString *code = [url substringFromIndex:from];
//        NSLog(@"%@", code);
        //根据code 获取一个 accessToken
        [self accessTokenWithCode:code];
        
        //不需要加载回调页面
        return NO;
    }

    return YES;
}

//根据code 获取一个 accessToken
- (void)accessTokenWithCode:(NSString *)code{
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *url = @"https://api.weibo.com/oauth2/access_token";
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    /*
     URL
     https://api.weibo.com/oauth2/access_token
     HTTP请求方式
     POST
     请求参数
     必选	类型及范围	说明
     client_id	true	string	申请应用时分配的AppKey。
     client_secret	true	string	申请应用时分配的AppSecret。
     grant_type	true	string	请求的类型，填写authorization_code
     code	true	string	调用authorize获得的code值。
     redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
     */
    params[@"client_id"] = HMAppKey;
    params[@"client_secret"] = HMAppSecret;
    params[@"grant_type"] = @"authorization_code";
    params[@"code"] = code;
    params[@"redirect_uri"] = HMRedirectUrl;
    
    [HMHttpTool post:url params:params success:^(id responseObj) {
        [MBProgressHUD hideHUD];
        /*
         {
         "access_token" = "2.00ZbHLGDLYpEZB1948f0d2921Ykm6B";
         "expires_in" = 157679999;//过期时间
         "remind_in" = 157679999;
         uid = 2839707357;//user_id / 当前登录用户的ID / 用户的唯一标识
         }
         */
        //授权成功,存储授权成功的账号信息
        HMAccount *account = [HMAccount accountWithDict:responseObj];
        [HMAccountTool save:account];
        
        //切换控制器
        //如果account 不为空,说明上次授权登录成功,无需再次登录
        [HMControllerTool chooseRootViewController];

    } failure:^(NSError *error) {
        //
        [MBProgressHUD hideHUD];
        
        [MBProgressHUD showError:@"获取数据失败!"];
        HMLog(@"%@", error);
    }];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
